package com.auok;

import com.auok.Entity.ConnectionRequest;
import com.auok.Entity.User;
import com.auok.Entity.UserSession;
import io.vertx.reactivex.core.http.ServerWebSocket;
import io.vertx.reactivex.ext.sql.SQLClient;
import io.vertx.reactivex.ext.web.Router;
import io.vertx.reactivex.ext.web.RoutingContext;


class WebSocketController {

    private SQLClient sqlClient;

    WebSocketController(SQLClient sqlClient) {
        this.sqlClient = sqlClient;
    }

    void Register(Router router) {
        router.route("/ws").handler(this::handleWebSocket);
    }

    private void handleWebSocket(RoutingContext ctx) {

        if (ctx.queryParam("sign") == null || ctx.queryParam("userid") == null) {
            ctx.response().setStatusCode(400).end();
            return;
        }

        String userId = ctx.queryParam("userid").get(0);
        String sign = ctx.queryParam("sign").get(0);

        long timestamp = Long.valueOf(ctx.queryParam("timestamp").get(0));

        if (!CheckSign(userId, sign, timestamp)) {
            ctx.response().setStatusCode(400).end();
            return;
        }

        ServerWebSocket ws = ctx.request().upgrade();

        if (ws != null) {
            User user = new User(userId);
            UserSession userSession = new UserSession(user, ws, sqlClient);

            ShareData.userSessions.put(userId, userSession);

            ws.closeHandler(h -> {
                ShareData.userSessions.remove(userId);
            });

//            for (UserSession session : ShareData.userSessions.values()) {
//                session.getWebSocket().writeTextMessage("新用户连接，Id：" + user.getId());
//            }

        }

    }


    /**
     * 验证签名
     *
     * @return
     */
    private boolean CheckSign(String userId, String sign, long timestamp) {


        ConnectionRequest connectionRequest = new ConnectionRequest(sign, userId, timestamp);

        //验证签名
        if (!connectionRequest.VerifySign()) {
            return false;
        }

        return true;
    }
}
